package com.zhoudy.segmetlock;


import java.util.*;
import java.util.concurrent.locks.Lock;

public class TransferData {

    private SegmentDataWithLock segmentDataWithLock  ;

    private  List<String> newDataContainer = new ArrayList<>(10);

   public TransferData(){
       segmentDataWithLock = new SegmentDataWithLock();
   }


    public void transfer(String key) {
        Lock lock = segmentDataWithLock.checkGetLock(key, false);
        if (lock == null) {
            System.out.println(key+" lock is null"+": "+Thread.currentThread().getName());
            return;
        }

        lock.lock();
        try {
            Map<String, String[]> segmentMap =  segmentDataWithLock.getSegmentMap();
            System.out.println(System.currentTimeMillis()+": "+Thread.currentThread().getName()+": transfer key("+key+")-> start, lock:"+ lock.toString());
            try {
                if (segmentMap.get(key) != null && segmentMap.get(key).length > 0) {
                    System.out.println(Thread.currentThread().getName()+":"+Arrays.asList(segmentMap.get(key) ));
//                    Random random = new Random();
//                    long time = random.nextInt(10000) ;
//                    Thread.sleep(time);

                    newDataContainer.addAll(Arrays.asList(segmentMap.get(key) ));
                }

                //删除数据和锁
                segmentDataWithLock.removeDataAndLockOfSegment(key);
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(System.currentTimeMillis()+": "+Thread.currentThread().getName()+": transfer key("+key+")-> complete "  );
        } finally {
            lock.unlock();
        }
    }


    public boolean isFinish(){
        return segmentDataWithLock.getSegmentMap().isEmpty() ;
    }

    public void segmentData(String[] data){
        segmentDataWithLock.blokFullWithSegmentation(data);
    }

    public  List<String> getNewDataContainer() {
        return newDataContainer;
    }

}


